<!--
 * @Author: your name
 * @Date: 2021-08-17 16:40:38
 * @LastEditTime: 2021-08-24 11:13:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue_study\src\views\shopcart\ShopCart.vue
-->
<template>
  <div>
    <NavBar class="nav-bar">
      <template v-slot:center>
        购物车(<span style="color: red"> {{ $store.state.cartCount }} </span>)
      </template>
    </NavBar>
    <div class="cart-box">
      <div class="cart-body">
        <van-checkbox-group ref="checkboxGroup" @change="groupChange" v-model="result">

          <van-swipe-cell :right-width="50"
            v-for="(item,index) in list" :key="index"
          >
            <div class="good-item">
              <van-checkbox :name="item.id" />
              <div class="good-img">
                <img :src="item.goods.cover_url" alt="" />
              </div>
              <div class="good-desc">
                <div class="good-title">
                  <span>{{item.goods.title}}</span>
                  <span>x{{item.goods.stock}}</span>
                </div>
                <div class="good-btn">
                  <div class="price"><small>￥</small>{{item.goods.price+'.00'}}</div>
                  <van-stepper
                    integer
                    :min="1"
                    :max="item.goods.stock"
                    :model-value="item.num"
                    :name="item.id"
                    async-change
                    @change="onChange"
                  ></van-stepper>
                </div>
              </div>
            </div>
            <template #right>
              <van-button
                square
                icon="delete"
                type="danger"
                class="delete-button"
                @click="deleteGood(item.id)"
              />
            </template>
          </van-swipe-cell>
          
        </van-checkbox-group>
      </div>
      <van-submit-bar class="submit-all" :price="total*100" button-text="结算" @submit="onSubmit">
        <van-checkbox v-model:checked="checkAll" @click="allCheck">全选</van-checkbox>
      </van-submit-bar>

      <div class="empty" v-show="!list.length">
          <img class="empty-cart" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fm.rongrong.cn%2Fstatic%2Fimg%2Fkong%403x.png" alt="空购物车">
          <div class="title">购物车空空如也</div>
          <van-button round color="#58D68D" type="primary" block @click="goTo">前往选购</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, torefs, onMounted, computed, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Toast } from "vant";
import { getCart ,deleteCartItem ,checkedCart ,modifyCart} from "network/cart";
import NavBar from "components/common/navbar/NavBar";
export default {
  name: "ShopCart",
  components: {
    NavBar,
  },
  setup() {
    const router = useRouter();
    const store = useStore();

    //数据模型（状态）
    const state=reactive({
        list:[],
        result:[],//id数组
        checkAll:true
    })

    //初始化购物车数据
    const init=()=>{
        Toast.loading({message:'加载中。。。',forbidClick:true})
        
        getCart('include=goods').then(res=>{
            state.list=res.data
            // console.log(res.data);
            
            state.result=res.data.filter((n)=>n.is_checked==1).map(item=>item.id);
            // console.log(state.result);

            Toast.clear()
        })
    }

    //复选框改变处理
    const groupChange=(result)=>{
        if(result.length==state.list.length){
            state.checkAll=true
        }else{
            state.checkAll=false
        }

        // console.log(result);
        state.result=result
        //改变数据表中的选中状态
        checkedCart({cart_ids:result})
    }

    onMounted(()=>{
        init()
    })

    //计算总价
    const total=computed(()=>{
        let sum=0

        state.list.filter(item=>state.result.includes(item.id)).forEach(item=>{
            sum+=parseInt(item.num)*parseFloat(item.goods.price)
        })

        return sum
    })

    const allCheck=()=>{
        if(!state.checkAll){
            state.result=state.list.map(item=>item.id)
            state.checkAll=true
        }else{
            state.result=[]
            state.checkAll=false
        }
    }

    //异步改变购物车熟练
    const onChange=(value,detail)=>{
        Toast.loading({message:'修改中。。。',forbidClick:true})
        // console.log(value);
        // console.log(detail.name);

        modifyCart(detail.name,{num:value}).then(res=>{
            //将list中的num改变
            state.list.forEach(item=>{
                if(item.id==detail.name){
                    item.num=value
                }
            })

            Toast.clear()
        })
    }

    //前往购物
    const goTo=()=>{
        router.push({path:"/home"})
    }

    //删除商品
    const deleteGood=(id)=>{
        deleteCartItem(id).then(res=>{
            //重新初始化
            init()
            //改变vuex中状态数量
            store.dispatch('updateCart')
        })
    }

    //创建订单
    const onSubmit=()=>{
        if(state.result.length===0){
            Toast.fail('没有可支付的订单')
            return
        }else{
            router.push({
                path:'/createorder'
            })
        }
    }

    return {
        ...toRefs(state),
        goTo,
        onChange,
        groupChange,
        allCheck,
        deleteGood,
        total,
        onSubmit
    };
  },
};
</script>

<style scoped lang="scss">
.cart-box {
  .cart-body {
    margin: 60px 0 100px 0;
    padding-left: 10px;
    .good-item {
      display: flex;
    }
    .good-img {
      img {
        width: 100px;
        height: auto;
      }
    }
    .good-desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      padding: 20px;
      .good-title {
        display: flex;
        justify-content: space-between;
      }
      .good-btn {
        display: flex;
        justify-content: space-between;
        .price {
          font-size: 16px;
          color: red;
          line-height: 28px;
        }
        .van-icon-delete {
          font-size: 20px;
          margin-top: 4px;
        }
      }
    }
    .delete-button {
      width: 50px;
      height: 100%;
    }
  }
  .empty {
    width: 50%;
    margin: 0 auto;
    text-align: center;
    margin-top: 200px;
    .empty-cart {
      width: 150px;
      margin-bottom: 50px;
    }
    .van-icon-smile-o {
      font-size: 50px;
    }
    .title {
      font-size: 16px;
      margin-bottom: 20px;
    }
  }
  .submit-all {
    margin-bottom: 55px;
    .van-checkbox {
      margin-left: o;
    }
    .van-submit-bar_text {
      margin-right: 10px;
    }
    .van-submit-bar_button {
      background: red;
    }
  }
  .van-checkbox_icon--checked .van-icon {
    background-color: red;
    border-color: red;
  }
}
</style>